import React, { useState } from 'react';
import { Icon, Button } from 'antd';
import { download } from '@/utils/utils';
import styles from './styles.less';
import { formatEllipsis, formatFileSize } from '../utils';
import { useFileDown } from '../hooks';

// 邮件附件组件
const Attachment = ({ attachmentList, type, onClick }) => {
    const [downLoadData, setDownLoadData] = useState(null); // 邮件列表数据源
    const [loading, data] = useFileDown(downLoadData);

    const currentMail = localStorage.getItem('currentMail'); // 获取当前绑定邮箱

    React.useEffect(() => {
        if (data) {
            download({
                getData: () => data
            });
        }
    }, [data]);

    return (
        <div className={styles.attachmentWrap}>
            {attachmentList.length > 0 &&
                attachmentList.map(item => (
                    <div className={styles.box} key={item.uid || item.fileName}>
                        <Icon type="file" className={styles.iconType} theme="filled" />
                        <ul>
                            <li>{formatEllipsis(item.fileName)}</li>
                            <li>{formatFileSize(item.fileSize)}</li>
                        </ul>

                        {type && (
                            <Button
                                loading={loading && downLoadData.uniqueCode === item.uniqueCode}
                                type="link"
                                icon={type === 'del' ? 'close' : 'download'}
                                className={styles.btn}
                                onClick={() => {
                                    if (type === 'down') {
                                        setDownLoadData({
                                            belongs: currentMail,
                                            uniqueCode: item.uniqueCode
                                        });
                                    }

                                    if (onClick) {
                                        onClick(item);
                                    }
                                }}
                            ></Button>
                        )}
                    </div>
                ))}
        </div>
    );
};
export default Attachment;
